{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Learning Embeddings with Continuous Bag of Words (CBOW)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from argparse import Namespace\n",
    "from collections import Counter\n",
    "import json\n",
    "import re\n",
    "import string\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import torch \n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "import torch.optim as optim\n",
    "from torch.utils.data import Dataset, DataLoader\n",
    "from tqdm import tqdm_notebook"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Data Vectorization classes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The Vocabulary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Vocabulary(object):\n",
    "    \"\"\"Class to process text and extract vocabulary for mapping\"\"\"\n",
    "\n",
    "    def __init__(self, token_to_idx=None, mask_token=\"<MASK>\", add_unk=True, unk_token=\"<UNK>\"):\n",
    "        \"\"\"\n",
    "        Args:\n",
    "            token_to_idx (dict): a pre-existing map of tokens to indices\n",
    "            mask_token (str): the MASK token to add into the Vocabulary; indicates\n",
    "                a position that will not be used in updating the model's parameters\n",
    "            add_unk (bool): a flag that indicates whether to add the UNK token\n",
    "            unk_token (str): the UNK token to add into the Vocabulary\n",
    "            \n",
    "        \"\"\"\n",
    "\n",
    "        if token_to_idx is None:\n",
    "            token_to_idx = {}\n",
    "        self._token_to_idx = token_to_idx\n",
    "\n",
    "        self._idx_to_token = {idx: token \n",
    "                              for token, idx in self._token_to_idx.items()}\n",
    "        \n",
    "        self._add_unk = add_unk\n",
    "        self._unk_token = unk_token\n",
    "        self._mask_token = mask_token\n",
    "        \n",
    "        self.mask_index = self.add_token(self._mask_token)\n",
    "        self.unk_index = -1\n",
    "        if add_unk:\n",
    "            self.unk_index = self.add_token(unk_token) \n",
    "        \n",
    "    def to_serializable(self):\n",
    "        \"\"\" returns a dictionary that can be serialized \"\"\"\n",
    "        return {'token_to_idx': self._token_to_idx, \n",
    "                'add_unk': self._add_unk, \n",
    "                'unk_token': self._unk_token, \n",
    "                'mask_token': self._mask_token}\n",
    "\n",
    "    @classmethod\n",
    "    def from_serializable(cls, contents):\n",
    "        \"\"\" instantiates the Vocabulary from a serialized dictionary \"\"\"\n",
    "        return cls(**contents)\n",
    "\n",
    "    def add_token(self, token):\n",
    "        \"\"\"Update mapping dicts based on the token.\n",
    "\n",
    "        Args:\n",
    "            token (str): the item to add into the Vocabulary\n",
    "        Returns:\n",
    "            index (int): the integer corresponding to the token\n",
    "        \"\"\"\n",
    "        if token in self._token_to_idx:\n",
    "            index = self._token_to_idx[token]\n",
    "        else:\n",
    "            index = len(self._token_to_idx)\n",
    "            self._token_to_idx[token] = index\n",
    "            self._idx_to_token[index] = token\n",
    "        return index\n",
    "            \n",
    "    def add_many(self, tokens):\n",
    "        \"\"\"Add a list of tokens into the Vocabulary\n",
    "        \n",
    "        Args:\n",
    "            tokens (list): a list of string tokens\n",
    "        Returns:\n",
    "            indices (list): a list of indices corresponding to the tokens\n",
    "        \"\"\"\n",
    "        return [self.add_token(token) for token in tokens]\n",
    "\n",
    "    def lookup_token(self, token):\n",
    "        \"\"\"Retrieve the index associated with the token \n",
    "          or the UNK index if token isn't present.\n",
    "        \n",
    "        Args:\n",
    "            token (str): the token to look up \n",
    "        Returns:\n",
    "            index (int): the index corresponding to the token\n",
    "        Notes:\n",
    "            `unk_index` needs to be >=0 (having been added into the Vocabulary) \n",
    "              for the UNK functionality \n",
    "        \"\"\"\n",
    "        if self.unk_index >= 0:\n",
    "            return self._token_to_idx.get(token, self.unk_index)\n",
    "        else:\n",
    "            return self._token_to_idx[token]\n",
    "\n",
    "    def lookup_index(self, index):\n",
    "        \"\"\"Return the token associated with the index\n",
    "        \n",
    "        Args: \n",
    "            index (int): the index to look up\n",
    "        Returns:\n",
    "            token (str): the token corresponding to the index\n",
    "        Raises:\n",
    "            KeyError: if the index is not in the Vocabulary\n",
    "        \"\"\"\n",
    "        if index not in self._idx_to_token:\n",
    "            raise KeyError(\"the index (%d) is not in the Vocabulary\" % index)\n",
    "        return self._idx_to_token[index]\n",
    "\n",
    "    def __str__(self):\n",
    "        return \"<Vocabulary(size=%d)>\" % len(self)\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self._token_to_idx)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "class CBOWVectorizer(object):\n",
    "    \"\"\" The Vectorizer which coordinates the Vocabularies and puts them to use\"\"\"    \n",
    "    def __init__(self, cbow_vocab):\n",
    "        \"\"\"\n",
    "        Args:\n",
    "            cbow_vocab (Vocabulary): maps words to integers\n",
    "        \"\"\"\n",
    "        self.cbow_vocab = cbow_vocab\n",
    "\n",
    "    def vectorize(self, context, vector_length=-1):\n",
    "        \"\"\"\n",
    "        Args:\n",
    "            context (str): the string of words separated by a space\n",
    "            vector_length (int): an argument for forcing the length of index vector\n",
    "        \"\"\"\n",
    "\n",
    "        indices = [self.cbow_vocab.lookup_token(token) for token in context.split(' ')]\n",
    "        if vector_length < 0:\n",
    "            vector_length = len(indices)\n",
    "\n",
    "        out_vector = np.zeros(vector_length, dtype=np.int64)\n",
    "        out_vector[:len(indices)] = indices\n",
    "        out_vector[len(indices):] = self.cbow_vocab.mask_index\n",
    "\n",
    "        return out_vector\n",
    "    \n",
    "    @classmethod\n",
    "    def from_dataframe(cls, cbow_df):\n",
    "        \"\"\"Instantiate the vectorizer from the dataset dataframe\n",
    "        \n",
    "        Args:\n",
    "            cbow_df (pandas.DataFrame): the target dataset\n",
    "        Returns:\n",
    "            an instance of the CBOWVectorizer\n",
    "        \"\"\"\n",
    "        cbow_vocab = Vocabulary()\n",
    "        for index, row in cbow_df.iterrows():\n",
    "            for token in row.context.split(' '):\n",
    "                cbow_vocab.add_token(token)\n",
    "            cbow_vocab.add_token(row.target)\n",
    "            \n",
    "        return cls(cbow_vocab)\n",
    "\n",
    "    @classmethod\n",
    "    def from_serializable(cls, contents):\n",
    "        cbow_vocab = \\\n",
    "            Vocabulary.from_serializable(contents['cbow_vocab'])\n",
    "        return cls(cbow_vocab=cbow_vocab)\n",
    "\n",
    "    def to_serializable(self):\n",
    "        return {'cbow_vocab': self.cbow_vocab.to_serializable()}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The Dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "class CBOWDataset(Dataset):\n",
    "    def __init__(self, cbow_df, vectorizer):\n",
    "        \"\"\"\n",
    "        Args:\n",
    "            cbow_df (pandas.DataFrame): the dataset\n",
    "            vectorizer (CBOWVectorizer): vectorizer instatiated from dataset\n",
    "        \"\"\"\n",
    "        self.cbow_df = cbow_df\n",
    "        self._vectorizer = vectorizer\n",
    "        \n",
    "        measure_len = lambda context: len(context.split(\" \"))\n",
    "        self._max_seq_length = max(map(measure_len, cbow_df.context))\n",
    "        \n",
    "        self.train_df = self.cbow_df[self.cbow_df.split=='train']\n",
    "        self.train_size = len(self.train_df)\n",
    "\n",
    "        self.val_df = self.cbow_df[self.cbow_df.split=='val']\n",
    "        self.validation_size = len(self.val_df)\n",
    "\n",
    "        self.test_df = self.cbow_df[self.cbow_df.split=='test']\n",
    "        self.test_size = len(self.test_df)\n",
    "\n",
    "        self._lookup_dict = {'train': (self.train_df, self.train_size),\n",
    "                             'val': (self.val_df, self.validation_size),\n",
    "                             'test': (self.test_df, self.test_size)}\n",
    "\n",
    "        self.set_split('train')\n",
    "\n",
    "    @classmethod\n",
    "    def load_dataset_and_make_vectorizer(cls, cbow_csv):\n",
    "        \"\"\"Load dataset and make a new vectorizer from scratch\n",
    "        \n",
    "        Args:\n",
    "            cbow_csv (str): location of the dataset\n",
    "        Returns:\n",
    "            an instance of CBOWDataset\n",
    "        \"\"\"\n",
    "        cbow_df = pd.read_csv(cbow_csv)\n",
    "        train_cbow_df = cbow_df[cbow_df.split=='train']\n",
    "        return cls(cbow_df, CBOWVectorizer.from_dataframe(train_cbow_df))\n",
    "\n",
    "    @classmethod\n",
    "    def load_dataset_and_load_vectorizer(cls, cbow_csv, vectorizer_filepath):\n",
    "        \"\"\"Load dataset and the corresponding vectorizer. \n",
    "        Used in the case in the vectorizer has been cached for re-use\n",
    "        \n",
    "        Args:\n",
    "            cbow_csv (str): location of the dataset\n",
    "            vectorizer_filepath (str): location of the saved vectorizer\n",
    "        Returns:\n",
    "            an instance of CBOWDataset\n",
    "        \"\"\"\n",
    "        cbow_df = pd.read_csv(cbow_csv)\n",
    "        vectorizer = cls.load_vectorizer_only(vectorizer_filepath)\n",
    "        return cls(cbow_df, vectorizer)\n",
    "\n",
    "    @staticmethod\n",
    "    def load_vectorizer_only(vectorizer_filepath):\n",
    "        \"\"\"a static method for loading the vectorizer from file\n",
    "        \n",
    "        Args:\n",
    "            vectorizer_filepath (str): the location of the serialized vectorizer\n",
    "        Returns:\n",
    "            an instance of CBOWVectorizer\n",
    "        \"\"\"\n",
    "        with open(vectorizer_filepath) as fp:\n",
    "            return CBOWVectorizer.from_serializable(json.load(fp))\n",
    "\n",
    "    def save_vectorizer(self, vectorizer_filepath):\n",
    "        \"\"\"saves the vectorizer to disk using json\n",
    "        \n",
    "        Args:\n",
    "            vectorizer_filepath (str): the location to save the vectorizer\n",
    "        \"\"\"\n",
    "        with open(vectorizer_filepath, \"w\") as fp:\n",
    "            json.dump(self._vectorizer.to_serializable(), fp)\n",
    "\n",
    "    def get_vectorizer(self):\n",
    "        \"\"\" returns the vectorizer \"\"\"\n",
    "        return self._vectorizer\n",
    "        \n",
    "    def set_split(self, split=\"train\"):\n",
    "        \"\"\" selects the splits in the dataset using a column in the dataframe \"\"\"\n",
    "        self._target_split = split\n",
    "        self._target_df, self._target_size = self._lookup_dict[split]\n",
    "\n",
    "    def __len__(self):\n",
    "        return self._target_size\n",
    "\n",
    "    def __getitem__(self, index):\n",
    "        \"\"\"the primary entry point method for PyTorch datasets\n",
    "        \n",
    "        Args:\n",
    "            index (int): the index to the data point \n",
    "        Returns:\n",
    "            a dictionary holding the data point's features (x_data) and label (y_target)\n",
    "        \"\"\"\n",
    "        row = self._target_df.iloc[index]\n",
    "\n",
    "        context_vector = \\\n",
    "            self._vectorizer.vectorize(row.context, self._max_seq_length)\n",
    "        target_index = self._vectorizer.cbow_vocab.lookup_token(row.target)\n",
    "\n",
    "        return {'x_data': context_vector,\n",
    "                'y_target': target_index}\n",
    "\n",
    "    def get_num_batches(self, batch_size):\n",
    "        \"\"\"Given a batch size, return the number of batches in the dataset\n",
    "        \n",
    "        Args:\n",
    "            batch_size (int)\n",
    "        Returns:\n",
    "            number of batches in the dataset\n",
    "        \"\"\"\n",
    "        return len(self) // batch_size\n",
    "    \n",
    "def generate_batches(dataset, batch_size, shuffle=True,\n",
    "                     drop_last=True, device=\"cpu\"): \n",
    "    \"\"\"\n",
    "    A generator function which wraps the PyTorch DataLoader. It will \n",
    "      ensure each tensor is on the write device location.\n",
    "    \"\"\"\n",
    "    dataloader = DataLoader(dataset=dataset, batch_size=batch_size,\n",
    "                            shuffle=shuffle, drop_last=drop_last)\n",
    "\n",
    "    for data_dict in dataloader:\n",
    "        out_data_dict = {}\n",
    "        for name, tensor in data_dict.items():\n",
    "            out_data_dict[name] = data_dict[name].to(device)\n",
    "        yield out_data_dict"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The Model: CBOW"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "class CBOWClassifier(nn.Module): # Simplified cbow Model\n",
    "    def __init__(self, vocabulary_size, embedding_size, padding_idx=0):\n",
    "        \"\"\"\n",
    "        Args:\n",
    "            vocabulary_size (int): number of vocabulary items, controls the\n",
    "                number of embeddings and prediction vector size\n",
    "            embedding_size (int): size of the embeddings\n",
    "            padding_idx (int): default 0; Embedding will not use this index\n",
    "        \"\"\"\n",
    "        super(CBOWClassifier, self).__init__()\n",
    "        \n",
    "        self.embedding =  nn.Embedding(num_embeddings=vocabulary_size, \n",
    "                                       embedding_dim=embedding_size,\n",
    "                                       padding_idx=padding_idx)\n",
    "        self.fc1 = nn.Linear(in_features=embedding_size,\n",
    "                             out_features=vocabulary_size)\n",
    "\n",
    "    def forward(self, x_in, apply_softmax=False):\n",
    "        \"\"\"The forward pass of the classifier\n",
    "        \n",
    "        Args:\n",
    "            x_in (torch.Tensor): an input data tensor. \n",
    "                x_in.shape should be (batch, input_dim)\n",
    "            apply_softmax (bool): a flag for the softmax activation\n",
    "                should be false if used with the Cross Entropy losses\n",
    "        Returns:\n",
    "            the resulting tensor. tensor.shape should be (batch, output_dim)\n",
    "        \"\"\"\n",
    "        x_embedded_sum = F.dropout(self.embedding(x_in).sum(dim=1), 0.3)\n",
    "        y_out = self.fc1(x_embedded_sum)\n",
    "        \n",
    "        if apply_softmax:\n",
    "            y_out = F.softmax(y_out, dim=1)\n",
    "            \n",
    "        return y_out"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training Routine"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Helper functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def make_train_state(args):\n",
    "    return {'stop_early': False,\n",
    "            'early_stopping_step': 0,\n",
    "            'early_stopping_best_val': 1e8,\n",
    "            'learning_rate': args.learning_rate,\n",
    "            'epoch_index': 0,\n",
    "            'train_loss': [],\n",
    "            'train_acc': [],\n",
    "            'val_loss': [],\n",
    "            'val_acc': [],\n",
    "            'test_loss': -1,\n",
    "            'test_acc': -1,\n",
    "            'model_filename': args.model_state_file}\n",
    "\n",
    "def update_train_state(args, model, train_state):\n",
    "    \"\"\"Handle the training state updates.\n",
    "\n",
    "    Components:\n",
    "     - Early Stopping: Prevent overfitting.\n",
    "     - Model Checkpoint: Model is saved if the model is better\n",
    "\n",
    "    :param args: main arguments\n",
    "    :param model: model to train\n",
    "    :param train_state: a dictionary representing the training state values\n",
    "    :returns:\n",
    "        a new train_state\n",
    "    \"\"\"\n",
    "\n",
    "    # Save one model at least\n",
    "    if train_state['epoch_index'] == 0:\n",
    "        torch.save(model.state_dict(), train_state['model_filename'])\n",
    "        train_state['stop_early'] = False\n",
    "\n",
    "    # Save model if performance improved\n",
    "    elif train_state['epoch_index'] >= 1:\n",
    "        loss_tm1, loss_t = train_state['val_loss'][-2:]\n",
    "\n",
    "        # If loss worsened\n",
    "        if loss_t >= train_state['early_stopping_best_val']:\n",
    "            # Update step\n",
    "            train_state['early_stopping_step'] += 1\n",
    "        # Loss decreased\n",
    "        else:\n",
    "            # Save the best model\n",
    "            if loss_t < train_state['early_stopping_best_val']:\n",
    "                torch.save(model.state_dict(), train_state['model_filename'])\n",
    "\n",
    "            # Reset early stopping step\n",
    "            train_state['early_stopping_step'] = 0\n",
    "\n",
    "        # Stop early ?\n",
    "        train_state['stop_early'] = \\\n",
    "            train_state['early_stopping_step'] >= args.early_stopping_criteria\n",
    "\n",
    "    return train_state\n",
    "\n",
    "def compute_accuracy(y_pred, y_target):\n",
    "    _, y_pred_indices = y_pred.max(dim=1)\n",
    "    n_correct = torch.eq(y_pred_indices, y_target).sum().item()\n",
    "    return n_correct / len(y_pred_indices) * 100"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### general utilities"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "def set_seed_everywhere(seed, cuda):\n",
    "    np.random.seed(seed)\n",
    "    torch.manual_seed(seed)\n",
    "    if cuda:\n",
    "        torch.cuda.manual_seed_all(seed)\n",
    "\n",
    "def handle_dirs(dirpath):\n",
    "    if not os.path.exists(dirpath):\n",
    "        os.makedirs(dirpath)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Settings and some prep work"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Expanded filepaths: \n",
      "\tmodel_storage/ch5/cbow/vectorizer.json\n",
      "\tmodel_storage/ch5/cbow/model.pth\n",
      "Using CUDA: True\n"
     ]
    }
   ],
   "source": [
    "args = Namespace(\n",
    "    # Data and Path information\n",
    "    cbow_csv=\"data/books/frankenstein_with_splits.csv\",\n",
    "    vectorizer_file=\"vectorizer.json\",\n",
    "    model_state_file=\"model.pth\",\n",
    "    save_dir=\"model_storage/ch5/cbow\",\n",
    "    # Model hyper parameters\n",
    "    embedding_size=50,\n",
    "    # Training hyper parameters\n",
    "    seed=1337,\n",
    "    num_epochs=100,\n",
    "    learning_rate=0.0001,\n",
    "    batch_size=32,\n",
    "    early_stopping_criteria=5,\n",
    "    # Runtime options\n",
    "    cuda=True,\n",
    "    catch_keyboard_interrupt=True,\n",
    "    reload_from_files=False,\n",
    "    expand_filepaths_to_save_dir=True\n",
    ")\n",
    "\n",
    "if args.expand_filepaths_to_save_dir:\n",
    "    args.vectorizer_file = os.path.join(args.save_dir,\n",
    "                                        args.vectorizer_file)\n",
    "\n",
    "    args.model_state_file = os.path.join(args.save_dir,\n",
    "                                         args.model_state_file)\n",
    "    \n",
    "    print(\"Expanded filepaths: \")\n",
    "    print(\"\\t{}\".format(args.vectorizer_file))\n",
    "    print(\"\\t{}\".format(args.model_state_file))\n",
    "    \n",
    "\n",
    "# Check CUDA\n",
    "if not torch.cuda.is_available():\n",
    "    args.cuda = False\n",
    "\n",
    "args.device = torch.device(\"cuda\" if args.cuda else \"cpu\")\n",
    "    \n",
    "print(\"Using CUDA: {}\".format(args.cuda))\n",
    "\n",
    "\n",
    "# Set seed for reproducibility\n",
    "set_seed_everywhere(args.seed, args.cuda)\n",
    "\n",
    "# handle dirs\n",
    "handle_dirs(args.save_dir)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Initializations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loading dataset and creating vectorizer\n"
     ]
    }
   ],
   "source": [
    "if args.reload_from_files:\n",
    "    print(\"Loading dataset and loading vectorizer\")\n",
    "    dataset = CBOWDataset.load_dataset_and_load_vectorizer(args.cbow_csv,\n",
    "                                                           args.vectorizer_file)\n",
    "else:\n",
    "    print(\"Loading dataset and creating vectorizer\")\n",
    "    dataset = CBOWDataset.load_dataset_and_make_vectorizer(args.cbow_csv)\n",
    "    dataset.save_vectorizer(args.vectorizer_file)\n",
    "    \n",
    "vectorizer = dataset.get_vectorizer()\n",
    "\n",
    "classifier = CBOWClassifier(vocabulary_size=len(vectorizer.cbow_vocab), \n",
    "                            embedding_size=args.embedding_size)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Training loop"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "code_folding": []
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "a9554f4cdbdb42a09e84106f394422de",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, description='training routine', style=ProgressStyle(description_width='ini…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "6c3e39531d5b45d39ed075f513bfbf9e",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, description='split=train', max=1984, style=ProgressStyle(description_width…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "50fc5a60e4624a3792e8cc14d940b3ab",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, description='split=val', max=425, style=ProgressStyle(description_width='i…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Exiting loop\n"
     ]
    }
   ],
   "source": [
    "classifier = classifier.to(args.device)\n",
    "    \n",
    "loss_func = nn.CrossEntropyLoss()\n",
    "optimizer = optim.Adam(classifier.parameters(), lr=args.learning_rate)\n",
    "scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer=optimizer,\n",
    "                                                 mode='min', factor=0.5,\n",
    "                                                 patience=1)\n",
    "train_state = make_train_state(args)\n",
    "\n",
    "epoch_bar = tqdm_notebook(desc='training routine', \n",
    "                          total=args.num_epochs,\n",
    "                          position=0)\n",
    "\n",
    "dataset.set_split('train')\n",
    "train_bar = tqdm_notebook(desc='split=train',\n",
    "                          total=dataset.get_num_batches(args.batch_size), \n",
    "                          position=1, \n",
    "                          leave=True)\n",
    "dataset.set_split('val')\n",
    "val_bar = tqdm_notebook(desc='split=val',\n",
    "                        total=dataset.get_num_batches(args.batch_size), \n",
    "                        position=1, \n",
    "                        leave=True)\n",
    "\n",
    "try:\n",
    "    for epoch_index in range(args.num_epochs):\n",
    "        train_state['epoch_index'] = epoch_index\n",
    "\n",
    "        # Iterate over training dataset\n",
    "\n",
    "        # setup: batch generator, set loss and acc to 0, set train mode on\n",
    "\n",
    "        dataset.set_split('train')\n",
    "        batch_generator = generate_batches(dataset, \n",
    "                                           batch_size=args.batch_size, \n",
    "                                           device=args.device)\n",
    "        running_loss = 0.0\n",
    "        running_acc = 0.0\n",
    "        classifier.train()\n",
    "\n",
    "        for batch_index, batch_dict in enumerate(batch_generator):\n",
    "            # the training routine is these 5 steps:\n",
    "\n",
    "            # --------------------------------------\n",
    "            # step 1. zero the gradients\n",
    "            optimizer.zero_grad()\n",
    "\n",
    "            # step 2. compute the output\n",
    "            y_pred = classifier(x_in=batch_dict['x_data'])\n",
    "\n",
    "            # step 3. compute the loss\n",
    "            loss = loss_func(y_pred, batch_dict['y_target'])\n",
    "            loss_t = loss.item()\n",
    "            running_loss += (loss_t - running_loss) / (batch_index + 1)\n",
    "\n",
    "            # step 4. use loss to produce gradients\n",
    "            loss.backward()\n",
    "\n",
    "            # step 5. use optimizer to take gradient step\n",
    "            optimizer.step()\n",
    "            # -----------------------------------------\n",
    "            # compute the accuracy\n",
    "            acc_t = compute_accuracy(y_pred, batch_dict['y_target'])\n",
    "            running_acc += (acc_t - running_acc) / (batch_index + 1)\n",
    "\n",
    "            # update bar\n",
    "            train_bar.set_postfix(loss=running_loss, acc=running_acc, \n",
    "                            epoch=epoch_index)\n",
    "            train_bar.update()\n",
    "\n",
    "        train_state['train_loss'].append(running_loss)\n",
    "        train_state['train_acc'].append(running_acc)\n",
    "\n",
    "        # Iterate over val dataset\n",
    "\n",
    "        # setup: batch generator, set loss and acc to 0; set eval mode on\n",
    "        dataset.set_split('val')\n",
    "        batch_generator = generate_batches(dataset, \n",
    "                                           batch_size=args.batch_size, \n",
    "                                           device=args.device)\n",
    "        running_loss = 0.\n",
    "        running_acc = 0.\n",
    "        classifier.eval()\n",
    "\n",
    "        for batch_index, batch_dict in enumerate(batch_generator):\n",
    "\n",
    "            # compute the output\n",
    "            y_pred =  classifier(x_in=batch_dict['x_data'])\n",
    "\n",
    "            # step 3. compute the loss\n",
    "            loss = loss_func(y_pred, batch_dict['y_target'])\n",
    "            loss_t = loss.item()\n",
    "            running_loss += (loss_t - running_loss) / (batch_index + 1)\n",
    "\n",
    "            # compute the accuracy\n",
    "            acc_t = compute_accuracy(y_pred, batch_dict['y_target'])\n",
    "            running_acc += (acc_t - running_acc) / (batch_index + 1)\n",
    "            val_bar.set_postfix(loss=running_loss, acc=running_acc, \n",
    "                            epoch=epoch_index)\n",
    "            val_bar.update()\n",
    "\n",
    "        train_state['val_loss'].append(running_loss)\n",
    "        train_state['val_acc'].append(running_acc)\n",
    "\n",
    "        train_state = update_train_state(args=args, model=classifier,\n",
    "                                         train_state=train_state)\n",
    "\n",
    "        scheduler.step(train_state['val_loss'][-1])\n",
    "\n",
    "        if train_state['stop_early']:\n",
    "            break\n",
    "\n",
    "        train_bar.n = 0\n",
    "        val_bar.n = 0\n",
    "        epoch_bar.update()\n",
    "except KeyboardInterrupt:\n",
    "    print(\"Exiting loop\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "# compute the loss & accuracy on the test set using the best available model\n",
    "\n",
    "classifier.load_state_dict(torch.load(train_state['model_filename']))\n",
    "classifier = classifier.to(args.device)\n",
    "loss_func = nn.CrossEntropyLoss()\n",
    "\n",
    "dataset.set_split('test')\n",
    "batch_generator = generate_batches(dataset, \n",
    "                                   batch_size=args.batch_size, \n",
    "                                   device=args.device)\n",
    "running_loss = 0.\n",
    "running_acc = 0.\n",
    "classifier.eval()\n",
    "\n",
    "for batch_index, batch_dict in enumerate(batch_generator):\n",
    "    # compute the output\n",
    "    y_pred =  classifier(x_in=batch_dict['x_data'])\n",
    "    \n",
    "    # compute the loss\n",
    "    loss = loss_func(y_pred, batch_dict['y_target'])\n",
    "    loss_t = loss.item()\n",
    "    running_loss += (loss_t - running_loss) / (batch_index + 1)\n",
    "\n",
    "    # compute the accuracy\n",
    "    acc_t = compute_accuracy(y_pred, batch_dict['y_target'])\n",
    "    running_acc += (acc_t - running_acc) / (batch_index + 1)\n",
    "\n",
    "train_state['test_loss'] = running_loss\n",
    "train_state['test_acc'] = running_acc\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Test loss: 8.50410728903378;\n",
      "Test Accuracy: 4.7720588235294095\n"
     ]
    }
   ],
   "source": [
    "print(\"Test loss: {};\".format(train_state['test_loss']))\n",
    "print(\"Test Accuracy: {}\".format(train_state['test_acc']))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Trained Embeddings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "def pretty_print(results):\n",
    "    \"\"\"\n",
    "    Pretty print embedding results.\n",
    "    \"\"\"\n",
    "    for item in results:\n",
    "        print (\"...[%.2f] - %s\"%(item[1], item[0]))\n",
    "\n",
    "def get_closest(target_word, word_to_idx, embeddings, n=5):\n",
    "    \"\"\"\n",
    "    Get the n closest\n",
    "    words to your word.\n",
    "    \"\"\"\n",
    "\n",
    "    # Calculate distances to all other words\n",
    "    \n",
    "    word_embedding = embeddings[word_to_idx[target_word.lower()]]\n",
    "    distances = []\n",
    "    for word, index in word_to_idx.items():\n",
    "        if word == \"<MASK>\" or word == target_word:\n",
    "            continue\n",
    "        distances.append((word, torch.dist(word_embedding, embeddings[index])))\n",
    "    \n",
    "    results = sorted(distances, key=lambda x: x[1])[1:n+2]\n",
    "    return results\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Enter a word: monster\n",
      "...[7.88] - saw\n",
      "...[7.89] - kid\n",
      "...[7.97] - truly\n",
      "...[7.97] - ultimately\n",
      "...[7.99] - cares\n",
      "...[8.01] - confused\n"
     ]
    }
   ],
   "source": [
    "word = input('Enter a word: ')\n",
    "embeddings = classifier.embedding.weight.data\n",
    "word_to_idx = vectorizer.cbow_vocab._token_to_idx\n",
    "pretty_print(get_closest(word, word_to_idx, embeddings, n=5))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=======frankenstein=======\n",
      "...[6.90] - dead\n",
      "...[6.96] - slight\n",
      "...[6.97] - oppressive\n",
      "...[7.02] - discrimination\n",
      "...[7.03] - spurned\n",
      "...[7.10] - illustrate\n",
      "=======monster=======\n",
      "...[7.88] - saw\n",
      "...[7.89] - kid\n",
      "...[7.97] - truly\n",
      "...[7.97] - ultimately\n",
      "...[7.99] - cares\n",
      "...[8.01] - confused\n",
      "=======science=======\n",
      "...[7.07] - impression\n",
      "...[7.15] - mutual\n",
      "...[7.17] - darkened\n",
      "...[7.19] - mist\n",
      "...[7.33] - swelling\n",
      "...[7.39] - tempted\n",
      "=======sickness=======\n",
      "...[6.37] - while\n",
      "...[6.56] - literally\n",
      "...[6.60] - foundations\n",
      "...[6.62] - probabilities\n",
      "...[6.69] - awoke\n",
      "...[6.69] - consoles\n",
      "=======lonely=======\n",
      "...[6.95] - moonlight\n",
      "...[6.97] - unveiled\n",
      "...[7.25] - ought\n",
      "...[7.26] - heartily\n",
      "...[7.30] - bed\n",
      "...[7.31] - undiscovered\n",
      "=======happy=======\n",
      "...[6.48] - bottom\n",
      "...[6.56] - chimney\n",
      "...[6.56] - injury\n",
      "...[6.65] - evening\n",
      "...[6.67] - lingered\n",
      "...[6.69] - chivalry\n"
     ]
    }
   ],
   "source": [
    "target_words = ['frankenstein', 'monster', 'science', 'sickness', 'lonely', 'happy']\n",
    "\n",
    "embeddings = classifier.embedding.weight.data\n",
    "word_to_idx = vectorizer.cbow_vocab._token_to_idx\n",
    "\n",
    "for target_word in target_words: \n",
    "    print(f\"======={target_word}=======\")\n",
    "    if target_word not in word_to_idx:\n",
    "        print(\"Not in vocabulary\")\n",
    "        continue\n",
    "    pretty_print(get_closest(target_word, word_to_idx, embeddings, n=5))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "_draft": {
   "nbviewer_url": "https://gist.github.com/7f86253a46c5444491fbb7541857edfa"
  },
  "gist": {
   "data": {
    "description": "chapters/06_RNN/tweet_classifcation/tweeter_classification.ipynb",
    "public": true
   },
   "id": "7f86253a46c5444491fbb7541857edfa"
  },
  "hide_input": false,
  "kernelspec": {
   "display_name": "nlpbook",
   "language": "python",
   "name": "nlpbook"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "nbTranslate": {
   "displayLangs": [
    "*"
   ],
   "hotkey": "alt-t",
   "langInMainMenu": true,
   "sourceLang": "en",
   "targetLang": "fr",
   "useGoogleTranslate": true
  },
  "notify_time": "30",
  "toc": {
   "colors": {
    "hover_highlight": "#DAA520",
    "running_highlight": "#FF0000",
    "selected_highlight": "#FFD700"
   },
   "moveMenuLeft": true,
   "nav_menu": {
    "height": "156px",
    "width": "252px"
   },
   "navigate_menu": true,
   "number_sections": true,
   "sideBar": false,
   "threshold": 4,
   "toc_cell": true,
   "toc_position": {
    "height": "255px",
    "left": "561px",
    "right": "20px",
    "top": "179px",
    "width": "266px"
   },
   "toc_section_display": "block",
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
